package com.demo.uploadpic_base64;

import java.io.File;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private View view;

	private ImageView imageView;

	private SelectPicPopupWindow menuWindow;

	private static ProgressDialog pd;

	/** 使用相机拍照获取图片 */
	private static final int SELECT_PIC_BY_TAKE_PHOTO = 1;

	/** 使用相册中的图片 */
	private static final int SELECT_PIC_BY_PICK_PHOTO = 2;

	private Uri photoUri;// 图片资源
	private String picPath;// 图片路径

	protected boolean isSuccess;// 图片上传是否成功
	
	private String resultCode;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();

			if (resultCode == "1") {
				Toast.makeText(MainActivity.this, "上传成功！！", Toast.LENGTH_LONG)
						.show();
			} else if (resultCode == "0") {
				Toast.makeText(MainActivity.this, "上传失败！！", Toast.LENGTH_LONG)
						.show();
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		view = LayoutInflater.from(this).inflate(R.layout.activity_main, null);

		imageView = (ImageView) findViewById(R.id.img);
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 从页面底部弹出一个窗口，选择拍照还是从相册选择已有图片
				menuWindow = new SelectPicPopupWindow(MainActivity.this,
						new OnClickListener() {

							@Override
							public void onClick(View v) {

								menuWindow.dismiss();// 隐藏弹出窗口
								switch (v.getId()) {
								case R.id.takePhotoBtn:// 拍照

									takePhoto();

									break;
								case R.id.pickPhotoBtn:// 选择相册图片

									pickPhoto();

									break;
								case R.id.cancelBtn:

									break;

								default:
									break;
								}

							}
						});

				menuWindow.showAtLocation(view, Gravity.TOP
						| Gravity.CENTER_HORIZONTAL, 0, 0);

			}
		});
	}

	/**
	 * 拍照
	 */
	protected void takePhoto() {

		if (SDCardUtils.isUsable()) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			/**
			 * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
			 * 如果不使用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
			 */
			ContentValues values = new ContentValues();
			photoUri = this.getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
			startActivityForResult(intent, SELECT_PIC_BY_TAKE_PHOTO);
		} else {
			Toast.makeText(MainActivity.this, "内存卡不存在！！", Toast.LENGTH_LONG)
					.show();
		}

	}

	/**
	 * 从相册中选择
	 */
	protected void pickPhoto() {

		Intent intent = new Intent();
		// “image/*”表示可以选择任意格式的图片
		intent.setType("image/png");
		intent.setAction(intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 点击取消按钮
		if (resultCode == this.RESULT_CANCELED) {
			return;
		}
		// 可以使用同一个方法，这里分开写是为了防止以后拓展不同的需求
		switch (requestCode) {
		case SELECT_PIC_BY_PICK_PHOTO:// 直接从相册获取

			doPhoto(requestCode, data);

			break;
		case SELECT_PIC_BY_TAKE_PHOTO:// 调用相机拍照

			doPhoto(requestCode, data);

			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图片获取和处理
	 * 
	 * @param requestCode
	 * @param data
	 */
	private void doPhoto(int requestCode, Intent data) {

		// 从相册获取图片，有些手机有异常情况，请注意
		if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
			photoUri = data.getData();
			if (data == null || photoUri == null) {
				Toast.makeText(MainActivity.this, "选择图片文件出错！！",
						Toast.LENGTH_LONG).show();
				return;
			}
		}

		String[] pojo = { MediaColumns.DATA };
		Cursor cursor = this.getContentResolver().query(photoUri, pojo, null,
				null, null);
		if (cursor != null) {
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);

			// 4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
			if (Integer.parseInt(Build.VERSION.SDK) < 14) {
				cursor.close();
			}
		}

		// 如果图片符合要求就将其上传到服务器
		if (picPath != null
				&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
						|| picPath.endsWith(".JPEG")
						|| picPath.endsWith(".jpeg")
						|| picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {

			BitmapFactory.Options options = new BitmapFactory.Options();

			// 设置一次采样为图片的边缘位置
			options.inJustDecodeBounds = true;

			// 压缩图片，表示缩略图大小为原始图片大小的几分之1,1为原图
			options.inSampleSize = 1;

			int outWidth = options.outWidth;
			int outHeight = options.outHeight;
			int width = (int) (200 * getResources().getDisplayMetrics().density);
			int height = width;

			// 设置当前压缩比例
			options.inSampleSize = Math.max(outWidth / width, outHeight
					/ height);

			options.inJustDecodeBounds = false;
			// 根据图片的SDCard路径读出bitmap、对图片压缩、二次采样
			final Bitmap bitmap = BitmapFactory.decodeFile(picPath, options);

			imageView.setImageBitmap(bitmap);

			pd = ProgressDialog.show(this, null, "正在上传,请稍后...");

			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						
						File file = new File(picPath);
						
						resultCode = UpLoadImage.uploadFile_01(file);

//						String fileName = picPath.substring(picPath
//								.lastIndexOf("/") + 1);
//						String uploadBuffer = ImageToBase64.imgToBase64(
//								picPath, bitmap);
//						Log.i("uploadBuffer", uploadBuffer);
//
//						String methodName = "FileUploadImage";
//
//						isSuccess = UpLoadImage.connectWebService(methodName,
//								fileName, uploadBuffer);

					} catch (Exception e) {
						e.printStackTrace();
					}

					// 执行耗时的方法之后发送消给handler
					handler.sendEmptyMessage(0);
				}
			}).start();

		} else {
			Toast.makeText(MainActivity.this, "选择的图片文件不正确...",
					Toast.LENGTH_LONG).show();
		}

	}

}
